﻿/*
 * MessageWriter.h
 */

#ifndef __GDK_MESSAGEWRITER_H__
#define __GDK_MESSAGEWRITER_H__


#include <gdk/core/Types.h>
#include <gdk/core/Exception.h>
#include <gdk/core/Callback.h>
#include <gdk/core/Stream.h>
#include <gdk/core/Message.h>
#include <gdk/core/Log.h>
#include <gdk/core/MessageReader.h>


namespace gdk
{



	class MessageWriter
	{
	public:
		typedef MessageReader::MessagePackage	MessagePackage;

	public:
		static bool push(OutputStream &os, const Message *msg)
		{
			GDK_ASSERT(msg != NULL);

			__TRY {

				os << msg->getClassId();
				msg->exportTo(os);
				return true;

			} __CATCH(e) {
				e.report();
			}
			return false;
		}
		//-----------------------------------------------
		static bool write(OutputStream &os, MessagePackage const &pkg)
		{
			__TRY
			{
				os << pkg._classId;

				ssize_t size = pkg._is.available();
				while (size > 0)
				{
					char buf[1024 * 64];
					ssize_t readSize = (size <= static_cast<ssize_t>(sizeof(buf))
								   	? size : static_cast<ssize_t>(sizeof(buf)));
					if (readSize != pkg._is.read(buf, readSize)
					||	readSize != os.write(buf, readSize))
					{
						return false;
					}
					size -= readSize;
				}
				return true;
			}
			__CATCH(e)
			{
				e.report();
			}

			return false;
		}
		//-----------------------------------------------
	};




}//namespace gdk


#endif //__GDK_MESSAGEWRITER_H__
